package licode.unisop.platform.application.executor;

import licode.unisop.platform.application.exception.PlatErrorCode;
import licode.unisop.platform.client.cache.PlatAuthCache;
import licode.unisop.platform.client.vo.PlatAuthVO;
import licode.unisop.platform.domain.PlatAuthItem;
import licode.unisop.platform.domain.PlatAuthManager;
import licode.unisop.provider.api.SiCacheProvider;
import licode.unisop.provider.info.SiPlatIdFind;
import licode.unisop.provider.utils.StrUtil;
import licode.unisop.types.CacheConf;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 内存缓存平台实现
 *
 * @author licode
 */
@Primary
@Component
public class PlatAuthCacheRedis implements PlatAuthCache, PlatAuthManager {
    @Resource
    private SiCacheProvider siCacheProvider;

    @Override
    public PlatAuthVO getPlatformById(SiPlatIdFind idInfo) {
        PlatAuthItem item;
        if (null == idInfo) {
            throw PlatErrorCode.PLATFORM_NOT_AUTH.buildThrow();
        }
        item = findPlatAuthItem(idInfo);

        return null == item ? null : item.getPlatformAuth();
    }

    @Override
    public void updatePlatform(PlatAuthVO plInfo) {
        PlatAuthItem item;
        item = findPlatAuthItem(SiPlatIdFind.builder()
                .platformId(plInfo.getPlatformId())
                .build());
        if (null != item) {
            item.setPlatformAuth(plInfo);
        }
    }

    @Override
    public int getAuthCount() {
        Object obj = siCacheProvider.get(CacheConf.AUTH_PLATFORM_COUNT);
        return null == obj ? 0 : Integer.parseInt(obj.toString());
    }

    @Override
    public List<PlatAuthVO> getAuthPlatforms() {
        return new ArrayList<>();
    }

    @Override
    public PlatAuthItem findPlatAuthItem(SiPlatIdFind idInfo) {
        return (PlatAuthItem)siCacheProvider.getObject(keyFromPlatIdInfo(idInfo));
    }

    @Override
    public void updatePlatAuthItem(PlatAuthItem authItem) {
        SiPlatIdFind idInfo = SiPlatIdFind.builder()
                .platformId(authItem.getPlatform().getId())
                .build();
        String key = keyFromPlatIdInfo(idInfo);
        siCacheProvider.setObject(key, authItem, -1);
    }

    @Override
    public void removePlatAuthItem(SiPlatIdFind idInfo) {
        siCacheProvider.deleteObject(keyFromPlatIdInfo(idInfo));
    }

    public String keyFromPlatIdInfo(SiPlatIdFind idInfo) {
        String platId = idInfo.getPlatformId();
        return StrUtil.isBlank(platId) ? "" : CacheConf.PLAT_PREFIX + platId;
    }
}
